<template>
    <el-form label-position="top" label-width="100px" :model="formLabelAlign" style="max-width: 460px">
        <el-form-item label="发送ID">
            <el-input v-model="formLabelAlign.SendId" />
        </el-form-item>
        <el-form-item label="接收ID|群聊ID">
            <el-input v-model="formLabelAlign.connectId" />
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click=connect>
                连接
            </el-button>
        </el-form-item>
        <el-form-item v-if ="isSocket">
            <el-button type="danger" @click=closeSocket>
                关闭连接
            </el-button>
        </el-form-item>
    </el-form>
    <el-card class="box-card">
        <template #header>
            <div class="card-header">
                <span>聊天窗口</span>
                <el-button class="button" text>当前在线2人</el-button>
            </div>
        </template>
        <div class="chat_box" :id=chat_box>
            <template v-for="item in data" :key="data.index">
                <div :class="[item.id == formLabelAlign.SendId ? 'chat_box_con_me' : '', 'chat_box_con']">
                    <img src="../../assets/images/head.png" alt="">
                    <div class="content_box">
                        <div class="nickname">{{ item.username }}</div>
                        <div class="content">{{ item.content }}</div>
                    </div>
                </div>
            </template>
        </div>
        <div class="send_box">
            <el-form ref="ruleFormRef" :model="form">
                <el-row>
                    <el-col :span="19">
                        <el-form-item prop="textarea" :rules="[
                            { required: true, message: '', trigger: 'blur' },
                        ]">
                            <el-input v-model="form.textarea" autosize type="textarea" placeholder="请输入内容" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="4" :offset="1">
                        <el-form-item>
                            <el-button type="primary" @click="onSubmit(ruleFormRef)">发送</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>
    </el-card>
</template>
<script setup >
import { watch, reactive, ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {WS_URL}from "@/config/index"
const props = defineProps(['chat_box','chat_type'])
const data = reactive([
    { id: 1, username: 'user', avatar: '', content: '开启聊天模式' },
    // { id: 2, username: 'user', avatar: '', content: 'adfdsgslenwlkh4o3;4ibvdsn lew4bsdfa' },
    // { id: 3, username: 'user', avatar: '', content: 'adfsdfa' },
    // { id: 4, username: 'user', avatar: '', content: 'adfsdfa' },
    // { id: 1, username: 'user', avatar: '', content: 'adfsdfa' },
])
const ruleFormRef = ref()
const formLabelAlign = reactive({
    SendId: '0000',
    connectId: '1234',
})
const form = reactive({
    textarea: '',
})
//是否连接状态
const isSocket = ref(false)
const onSubmit = async (formEl) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            sendMsg()
            // scroll()           
        } else {
            // console.log(fields)
            ElMessage.error('输入框不能为空.')
        }
    })
}
const resetForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
}
const sendMsg = () => {
    if (!isSocket) {
        ElMessage.error('socket没有连接.')
        return
    }
    console.log('sendMsg')
    data.push({ id: formLabelAlign.SendId, username: 'user', avatar: '', content: form.textarea })

    let sendData = {
        type: props.chat_type,
        uid: formLabelAlign.connectId,
        message: form.textarea
    }
    socket.send(JSON.stringify(sendData))
    form.textarea = null
}
const scroll = () => {
    let ele = document.getElementById(props.chat_box);
    //判断元素是否出现了滚动条
    if (ele.scrollHeight > ele.clientHeight) {
        //设置滚动条到最底部
        ele.scrollTop = ele.scrollHeight - 20;
    }
}
//加入群聊
const jionChat = () =>{
    socket.send('{"type":"join","group":"1234"}')
}

//监听数据变化,触发滚动条
watch(data, () => {
    scroll()
});
let socket
const connect = () => {
    const address = `${WS_URL}?token=${formLabelAlign.SendId}`
    console.log(address)
    if (window.WebSocket) {
        socket = new WebSocket(address)
        //相当于channelRead0，ev收到服务器端回送的消息
        socket.onmessage = ev => {
            let jsonObj = JSON.parse(ev.data);
            if (jsonObj.type == 'ping') {
                socket.send('{"type":"pong"}')
            }
            if (jsonObj.type == 'send_msg' ||jsonObj.type == 'send_to_uid') {
                data.push(jsonObj.content)
            }
        }
        // 连接开启
        socket.onopen = ev => {
            isSocket.value = true
            ElMessage({
                type: 'success',
                message: '连接成功',
            })
            if(props.chat_type == 'send_to_group')
            {
                jionChat()
            }
            console.log('连接开启了...')
        }
        // 感知到连接关闭
        socket.onclose = ev => {
            open()
            console.log('连接关闭了...')
            isSocket.value = false
        }
    } else {
        alert('当前的浏览器不支持webSocket')
    }
}
const open = () => {
    ElMessageBox.confirm(
        '检测到你已经离线,是否重新连接?',
        '注意',
        {
            confirmButtonText: '是',
            cancelButtonText: '否',
            type: 'warning',
        }
    )
        .then(() => {

            connect()
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消连接',
            })
        })
}
// 关闭连接
const closeSocket = ()=>{
    socket.close();
}
</script>
<style scoped lang="scss">
.chat_box_con:last-child {
    margin-bottom: 70px;
}

.send_box {
    // display: flex;
    margin: 10px;
    padding: 10px;
    background-color: #F0F2F5;
}

.box-card:hover {
    ::-webkit-scrollbar {
        width: 5px;
    }
}

::-webkit-scrollbar {
    width: 0px;
    /* 滚动条宽度 */
    height: 100px;
    /* 滚动条高度 */
    background-color: #E6A23C;
    /* 滚动条背景颜色 */
    border: 1px solid #ccc;
    /* 滚动条边框样式 */
    border-radius: 10px;
}

::-webkit-scrollbar-thumb {
    background-color: #409EFF;
    /* 滑块颜色 */
    border-radius: 10px;
    /* 滑块圆角 */
}

.chat_box {
    width: 100%;
    height: 300px;
    overflow-y: scroll;

    .chat_box_con {
        width: 100%;
        display: flex;
        margin-top: 5px;

        img {
            margin-top: 10px;
            margin-right: 5px;
            width: 45px;
            height: 45px;
        }

        .content_box {
            margin: 5px;
            // width: 100%;
            max-width: 70%;

            .nickname {
                font-size: 14px;
                color: #606266;
            }

            .content {
                width: auto;
                padding: 5px;
                // margin: 5px;
                font-size: 20px;
                color: #303133;
                overflow-wrap: break-word;
                background-color: rgba(140, 198, 242, 0.1);
            }
        }
    }

    .chat_box_con_me {
        flex-direction: row-reverse;
        justify-content: end;

        .content_box {
            .nickname {
                display: none;
            }

            .content {
                margin-top: 10px;
            }
        }
    }
}
</style>